//简单的socket客户端
package main

import (
	"fmt"
	"net"
	"os"
	"strings"
)

var str string
var msg = make([]byte, 1024)
var (
	host   = "127.0.0.1"
	port   = "6666"
	remote = host + ":" + port
)

func main() {
	Setport()
	con, err := net.Dial("tcp", remote)
	//defer con.Close()
	if err != nil {
		fmt.Println("Server not found.")
		os.Exit(-1)
	}
	fmt.Println("Connection OK.")
	for {
		//接收输入
		fmt.Printf("Enter a sentence:")
		//in, err1 := fmt.Scanf("%s\n", &str)

		input := make([]byte, 1024)
		length, _ := os.Stdin.Read(input)
		str = string(input[0 : length-1])
		//fmt.Println(length)
		if length == 1 {
			fmt.Println("请输入内容!")
			continue
		}

		//如果是quit就结束链接
		if str == "quit" {
			fmt.Println("Communication terminated.")
			os.Exit(1)
		}
		//发送内容给服务器
		in, err := con.Write([]byte(str))
		if err != nil {
			fmt.Printf("Error when send to server: %d\n", in)
			os.Exit(0)
		}
		////接收服务器的内容
		//length, err2 := con.Read(msg)
		//if err2 != nil {
		//	fmt.Printf("Error when read from server.\n")
		//	os.Exit(0)
		//}
		//str = string(msg[0:length])
		//fmt.Println(str)
		//接收服务器的内容
		//for {
		//	length, err2 := con.Read(msg)
		//	if err2 != nil {
		//		fmt.Printf("Error when read from server.\n")
		//		os.Exit(0)
		//	}
		//	str = string(msg[0:length])
		//	fmt.Println(str)
		//	con.Write([]byte("00"))
		//}
		for {
			length, err2 := con.Read(msg)
			if err2 != nil {
				fmt.Printf("Error when read from server.\n")
				os.Exit(0)
			}
			str = string(msg[0:length])
			fmt.Println(str)
			//con.Write([]byte("112345678920        8151355839022517280               01232#"))
			if str == "00" {
				fmt.Println("00")
				con.Write([]byte("00"))
			} else {
				sf := strings.Fields(str)
				content := sf[2]
				contents := strings.Split(content, ":")
				//id := string(contents[1:])
				id := contents[0][1:]
				word := "112345678920        8151355839022517280               0" + id + "#"
				fmt.Println(word)
				con.Write([]byte(word))
			}
		}
	}
}

func Setport() {
	fmt.Println("请输入ip地址:")
	_, err1 := fmt.Scanln(&host)
	if err1 != nil {
		host = "218.241.25.189"
	}
	fmt.Println("请输入端口号port:")
	_, err2 := fmt.Scanln(&port)
	if err2 != nil {
		//fmt.Println("输入为空")
		port = "6666"
	}
	remote = host + ":" + port
	fmt.Printf("正在为您链接远端服务器=%s\n", remote)
}
